package cn.sunxiansheng.publisher.pub;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * Description: 测试发布者
 *
 * @Author sun
 * @Create 2024/12/31 19:05
 * @Version 1.0
 */
@RestController
@Slf4j
public class TestConfigPublisher {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @RequestMapping("/send")
    public void send() {
        log.info("发送消息");
        // 1.创建CorrelationData对象
        CorrelationData cd = new CorrelationData(UUID.randomUUID().toString());
        // 2.设置回调
        cd.getFuture().addCallback(new ListenableFutureCallback<CorrelationData.Confirm>() {
            @Override
            public void onFailure(Throwable throwable) {
                // 基本不可能发生，因为这里的异常不是MQ问题导致的
                log.error("ConfirmCallback：消息发送失败(非MQ问题):{}", throwable.getMessage());
            }

            @Override
            public void onSuccess(CorrelationData.Confirm confirm) {
                // 判断是否发送成功
                if (confirm.isAck()) {
                    log.info("ConfirmCallback：消息发送成功:{}", confirm);
                } else {
                    log.error("ConfirmCallback：消息发送失败:{}", confirm.getReason());
                }
            }
        });
        rabbitTemplate.convertAndSend("fanout.exchange.test", "", "hello rabbitmq", cd);
    }

    @RequestMapping("/send2")
    public void send2() {
        log.info("发送消息");
        // 1.创建CorrelationData对象
        CorrelationData cd = new CorrelationData(UUID.randomUUID().toString());
        // 2.设置回调
        cd.getFuture().addCallback(new ListenableFutureCallback<CorrelationData.Confirm>() {
            @Override
            public void onFailure(Throwable throwable) {
                // 基本不可能发生，因为这里的异常不是MQ问题导致的
                log.error("ConfirmCallback：消息发送失败(非MQ问题):{}", throwable.getMessage());
            }

            @Override
            public void onSuccess(CorrelationData.Confirm confirm) {
                // 判断是否发送成功
                if (confirm.isAck()) {
                    log.info("ConfirmCallback：消息发送成功:{}", confirm);
                } else {
                    log.error("ConfirmCallback：消息发送失败:{}", confirm.getReason());
                }
            }
        });
        rabbitTemplate.convertAndSend("elk.exchange", "", "hello rabbitmq", cd);
    }
}